<template>
  <BasicModal
      :title="title"
      :width="700"
      v-bind="$attrs"
      @ok="handleOk"
      @register="registerModal">
    <BasicForm @register="registerForm"/>
  </BasicModal>
  <PreviewCodeModel @register="previewCodeModel" />
</template>


<script lang="ts" setup>
import { watch, computed, inject, ref, unref, onMounted } from 'vue'

import { BasicForm, useForm } from '/@/components/Form/index'
import { BasicModal, useModalInner } from '/@/components/Modal'
import PreviewCodeModel from './PreviewCodeModel.vue';
import {useModal} from '/@/components/Modal';
import { genCode, getGenInfo } from '../codeGen.api'
import { genCodeFormSchema } from '../codeGen.data'
import { listTemplateGroup } from '../../code-template-group/code.template.group.api';
import { listByGroupId } from '../../codeTemplate/code.template.api';
import { useMessage } from '/@/hooks/web/useMessage'
const { createMessage } = useMessage()
const emit = defineEmits(['success', 'register'])
const props = defineProps({
  rootTreeData: { type: Array, default: () => [] },
})
// 当前是否是更新模式
const isUpdate = ref<boolean>(false)
// 当前的弹窗数据
// const model = ref<object>({})
const title = computed(() => '生成代码')

//注册表单
const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
  schemas: genCodeFormSchema,
  showActionButtonGroup: false,
})

const [previewCodeModel, {openModal: openPreviewCodeModel}] = useModal();

// 注册弹窗
const [registerModal, { setModalProps, closeModal }] = useModalInner(async data => {
  await resetFields()
  const {id} = unref(data)
  // 获取所有模板组
  const templateGropp = await listTemplateGroup({})
  updateSchema([
    { 
      field: 'templateGroupId',
      componentProps: ({ formModel, formActionType }) => {
        return {
          optionFilterProp: "label",
            showSearch: true,
            options: templateGropp,
          onChange: async (templateGroupId: any) => {
            const { updateSchema } = formActionType;
            formModel.templateIds = undefined; //  reset value
            if (!templateGroupId) {
              return
            }
            const templateList = await listByGroupId({groupId: templateGroupId});
            
            updateSchema({
              field: 'templateIds',
              componentProps: {
                optionFilterProp: "label",
                showSearch: true,
                options: templateList,
              },
            });
          },
        };
      },
    }
  ])
  
  
  // 获取生成信息
  const genInfo = await getGenInfo(id)

  // 赋默认值
  await setFieldsValue({genTableId: id, ...genInfo})
})

// 提交事件
async function handleOk() {
  try {
    setModalProps({ confirmLoading: true })
    let values = await validate()
    console.log("gen code from: ", values)
    const codeList = await genCode(values)
    openPreviewCodeModel(true, {list: codeList})
    //提交表单
    // await saveOrUpdateDepart(values, isUpdate.value)
    //关闭弹窗
    closeModal()
    //刷新列表
    emit('success')
  } finally {
    setModalProps({ confirmLoading: false })
  }
}
</script>